package com.lyq.interaction.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtil {
    private static final long DURING_TIME = 1000*60*60*24;
    private static final String STR = "7pphFphDj5GK12AE9R7/y723Cx7hujdhDy/eDV7MLM4=";
    private static final Key KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode(STR));

    public static String getToken(Map<String, Object> map) {
        String token = Jwts.builder()
                .addClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + DURING_TIME))
                .signWith(KEY)
                .compact();
        return token;
    }

    public static Claims checkToken(String token) {
        Claims body = null;
        try{
            body = Jwts.parserBuilder()
                    .setSigningKey(KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        }catch (ExpiredJwtException e) {
            log.warn("token 令牌过期 ：{}", e.getMessage());
            throw new RuntimeException("token 令牌过期");
        }catch (Exception e) {
            log.warn("token 令牌解析异常 ：{}", e.getMessage());
            throw new RuntimeException("token 令牌解析异常");
        }
        return body;
    }
}
